#pragma once
#include <highgui.h>
#include "stdlib.h"
#include "FrameKey.h"

class BaseVideoManager
{
	CvCapture* _capture;	
	bool _isFirstFrame;
	std::vector<FrameKey*> _frameKeys;
	int _waitTime;

public:
	BaseVideoManager(const char* videoFilePath) : _isFirstFrame(true)
	{
		_capture = cvCaptureFromAVI(videoFilePath);
		if (_capture == NULL)
		{
			printf("Can't open video file.\r\n");
			throw "Exception: video file not found";
		}
	}

	virtual void OnFrame(FrameKey* key, IplImage* frame) = 0;
	virtual void OnFirstFrame(FrameKey* key, IplImage* frame) { }

	virtual void StartPlay()
	{
		char b;
		do
		{
			IplImage* frame = cvQueryFrame(_capture);
			cvQueryFrame(_capture);
			cvQueryFrame(_capture);
			cvQueryFrame(_capture);

			FrameKey* key = FrameKey::NewKey();
			_frameKeys.push_back(key);
	
			if (frame == NULL)
				break;

			if (_isFirstFrame)
			{
				OnFirstFrame(key, frame);
				_isFirstFrame = false;
			}
			else
				OnFrame(key, frame);

			b = cvWaitKey(_waitTime);
			if (b == 'm')
				_waitTime = _waitTime == 1 ? 0 : 1;
			OnKeyPress(b);			

		} while (b != 27);
	}

	virtual void OnKeyPress(char key)
	{
	}

	virtual ~BaseVideoManager()
	{
		cvReleaseCapture(&_capture);
	}
};